package com.answer.service.scoring;

import com.answer.common.ErrorCode;
import com.answer.entity.App;
import com.answer.entity.UserAnswer;
import com.answer.exception.BusinessException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评分策略执行器
 */
@Service
public class ScoringStrategyExecutor {

    // 策略列表
    @Resource
    private List<ScoringStrategy> scoringStrategyList;

    /**
     * 根据用户选择和应用信息进行评分
     *
     * @param choiceList 用户的选择列表，用于评分策略的计算
     * @param app 应用实例，包含应用类型和评分策略信息
     * @return 返回用户的评分结果
     * @throws Exception 当应用配置有误或找不到匹配策略时抛出异常
     */
    public UserAnswer doScore(List<String> choiceList, App app) throws Exception {
        // 获取应用类型和应用评分策略
        Integer appType = app.getAppType();
        Integer appScoringStrategy = app.getScoringStrategy();
        // 检查应用类型和评分策略是否为空
        if (appType == null || appScoringStrategy == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "应用配置有误，未找到匹配的策略");
        }
        // 遍历所有评分策略，根据注解匹配应用类型和评分策略
        for (ScoringStrategy strategy : scoringStrategyList) {
            if (strategy.getClass().isAnnotationPresent(ScoringStrategyConfig.class)) {
                ScoringStrategyConfig scoringStrategyConfig = strategy.getClass().getAnnotation(ScoringStrategyConfig.class);
                // 当策略匹配应用类型和评分策略时，执行评分并返回结果
                if (scoringStrategyConfig.appType() == appType && scoringStrategyConfig.scoringStrategy() == appScoringStrategy) {
                    return strategy.doScore(choiceList, app);
                }
            }
        }
        // 当找不到匹配的策略时，抛出异常
        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "应用配置有误，未找到匹配的策略");
    }
}
